<?php
/**
 * 开放平台的 component
 */
namespace App\Models\OpenWechat;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

/**
 * Class ComponentToken
 *
 * @property string component_access_token - 开放平台 token
 * @property string component_verify_ticket - wechat推送过来的ticket
 * @property Carbon ticket_updated_at - ticket的更新时间, 10分钟更新一次
 * @property Carbon token_should_refresh - 如当前时间超过此值, token当刷新
 *
 * @package App\Models\OpenWechat
 */
class ComponentToken extends Model
{
    protected $table = 'component_tokens';

    protected static $unguarded = true;

    /**
     * 更新对应平台的 ticket
     *
     * @param $ticket
     * @param $appid
     * @return bool
     */
    public static function updatePlatformVerifyTicket($appid, $ticket)
    {
        $component = self::findByAppId($appid);

        if (! $component) return false;

        return $component->updateCompVerifyTicket($ticket);
    }

    /**
     * @param $ticket
     * @return bool
     */
    public function updateCompVerifyTicket($ticket)
    {
        return $this->update([
                'component_verify_ticket' => $ticket
            ]);
    }

    /**
     * @param $appid
     * @return Model|null|static
     */
    public static function findByAppId($appid)
    {
        return self::where('appid' , $appid)->first();
    }

    /**
     * @param string $token
     * @return bool
     */
    public function updateAccessToken($token)
    {
        return $this->update([
            'component_access_token' => $token,
        ]);
    }
}
